<template>
  <div style="opacity: 0.88;">
    <div class="manage-form">
      <div class="manage-title">
        <h2>管理用户信息</h2>
      </div>
      <div class="search-container" style="margin-bottom: 20px;">
        <el-input v-model="searchName" placeholder="按用户名查找用户" style="width: 300px; margin-right: 20px;" />
        <el-button @click="searchProduct">搜索</el-button>
      </div>
      <el-table :data="paginatedData" style="width: 100%">
        <el-table-column label="编号" prop="no" />
        <el-table-column label="账号" prop="username" />
        <el-table-column label="密码">
          <template v-slot="{ row, $index }">
            <span>{{ passwordVisibility[$index] ? row.password : '⋯⋯' }}</span>
            <div class="action-buttons">
              <el-button @click="togglePasswordVisibility($index)" type="text">
                {{ passwordVisibility[$index] ? '隐藏密码' : '显示密码' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="120">
          <template v-slot="{ row }">
            <div class="action-buttons">
              <el-button @click="confirmDeleteUser(row.username)" type="danger" >删除用户</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="filteredData.length"
        layout="total, prev, pager, next, jumper"
      ></el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';

const router = useRouter();
const tableData = ref([]);
const dialogFormVisible = ref(false);
const editForm = ref({ id: '', username: '', password: '' });
const currentPage = ref(1);
const pageSize = ref(10);
const searchName = ref('');
const passwordVisibility = ref([]); 

const fetchData = async () => { 
  try {
    const response = await axios.get('http://localhost:8080/getuser');
    console.log(response.data);
    if (Array.isArray(response.data)) {
      tableData.value = response.data.map((value, index) => ({
        no: index + 1,
        password: value.password,
        username: value.username,
      }));
      passwordVisibility.value = new Array(response.data.length).fill(false);
    } else {
      console.error('返回值不为数组:', response.data);
    }
  } catch (error) {
    console.error('发生了错误:', error);
  }
};

const togglePasswordVisibility = (index) => {
  passwordVisibility.value[index] = !passwordVisibility.value[index];
};

const searchProduct = () => {
  currentPage.value = 1;
};

const filteredData = computed(() => {
  return tableData.value.filter(User => {
    return User.username.toLowerCase().includes(searchName.value.toLowerCase());
  });
});

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

const handleCurrentChange = (page) => {
  currentPage.value = page;
};

const confirmDeleteUser = (username) => {
  ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => {
    deleteUser(username);
    ElMessage.success('删除成功！');
  })
  .catch(() => {
    ElMessage.info('已取消删除');
  });
};

const deleteUser = async (username) => {
  try {
    await axios.post(`http://localhost:8080/deleteuser?username=${username}`);
    await fetchData();
    ElMessage.success('删除成功！');
  } catch (error) {
    console.error('Error deleting user:', error);
    ElMessage.error('删除失败');
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.manage-form .manage-title {
  font-size: 2em;
  text-align: center;
  text-shadow: 5px 5px 5px #4161d5;
}

.manage-form {
  background-color: aliceblue;
}

.search-container {
  text-align: right;
}

.action-buttons {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>